<template>
  <div id="app"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { getDatasets } from '@/api/historyData.js';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      // 历史数据
      datasets: null,
      // map 地图对象实例
      map: null,
    };
  },
  mounted() {
    this._createBaseMap();
  },
  methods: {
    _createBaseMap() {
      mapboxgl.accessToken =
        'pk.eyJ1IjoiY2hhbnBmIiwiYSI6ImNsNG1qMDExejAwNDgzam8zcGtiMW5sNmwifQ.J4K5kbkjtcAABsmIW7Z0Tw';

      const map = new mapboxgl.Map({
        container: 'app',
        //自己绘制的样式地图令牌
        antialias: true, //抗锯齿
        style: 'mapbox://styles/mapbox/dark-v10',
        center: [113.97923191113188, 22.589860256941634],
        // center: [-75.789, 41.874],
        zoom: 12,
        // maxZoom: 5.99,
        // minZoom: 4,
        // zoom: 5,
      });

      this.map = map;
      window.map = map;

      // const taskArr = [];
      // const sectionRange = [1, 3];
      // for (let i = 1; i <= sectionRange[1]; i++) {
      //   taskArr.push(getDatasets(`../sections/section${i}.geojson`));
      // }

      getDatasets('../section1.geojson').then((data) => {
        // 先拿到起始时间
        const startTime = dayjs(data.features[0].properties?.samplingTime);
        console.log('startTime :>> ', startTime);
        // 再次稀释
        // data.features = data.features.filter((item, index) => {
        //   if (index % 2 === 0) {
        //     return item;
        //   }
        // });

        // data.features = data.features.filter((item, index) => {
        //   if (index % 2 === 0) {
        //     return item;
        //   }
        // });
        data.features = data.features.filter((item, index) => {
          if (index % 2 === 0) {
            return item;
          }
        });

        console.log('data :>> ', data);
        const featuresLen = data.features.length;
        // 结束时间
        const endTime = dayjs(
          data.features[featuresLen - 1].properties?.samplingTime
        );
        console.log('endTime :>> ', endTime);

        const COLOR_LEVEL = [
          'rgba(0,255,0,0.7)',
          'rgba(255,255,255,0.7)',
          'rgba(255,125,0,0.7)',
          'rgba(255,0,0,0.7)',
          'rgba(152,0,75,0.7)',
          'rgba(178,24,43,0.7)',
        ];
        map.on('load', () => {
          map.addSource('points-source', {
            type: 'geojson',
            data,
          });

          map.addLayer({
            id: 'points-layer',
            type: 'circle',
            source: 'points-source',
            // 'source-layer': 'section0',
            paint: {
              // Size circle radius by earthquake magnitude and zoom level  大小圈半径由 PM2.5 和缩放级别共同决定
              'circle-radius': [
                'interpolate',
                ['linear'],
                ['zoom'],
                9,
                ['interpolate', ['linear'], ['get', 'PM2D5'], 500, 1],
                10,
                // ['interpolate', ['linear'], ['get', 'mag'], 1, 5, 6, 50],
                ['interpolate', ['linear'], ['get', 'PM2D5'], 500, 0.5],
                18,
                12,
              ],
              // Color circle by earthquake magnitude  用颜色标出 PM2.5 的污染程度
              'circle-color': [
                'interpolate',
                ['linear'],
                ['get', 'PM2D5'],
                50,
                COLOR_LEVEL[0],
                100,
                COLOR_LEVEL[1],
                150,
                COLOR_LEVEL[2],
                200,
                COLOR_LEVEL[3],
                300,
                COLOR_LEVEL[4],
                500,
                COLOR_LEVEL[5],
              ],
              'circle-stroke-color': 'transparent',
              'circle-stroke-width': 0, // 圆点的边框大小
              // Transition from heatmap to circle layer by zoom level  通过缩放级别从热图过渡到圆圈层
              'circle-opacity': [
                'interpolate',
                ['linear'],
                ['zoom'],
                // zoom 比9小隐藏
                9,
                0,
                // 否则显示
                10,
                1,
              ],
            },
          });

          // function filterBy(mapInstance, showMinutes) {
          //   const filters = ['==', 'showMinutes', showMinutes];
          //   mapInstance.setFilter('points-layer', filters);
          // }

          let step = 0;
          let lastStep = data.features[featuresLen - 1].properties?.stepFlag;
          console.log('lastStep :>> ', lastStep);
          const filters = ['==', 'stepFlag', step];
          setInterval(() => {
            // filterBy(map, step);
            filters[2] = step;
            map.setFilter('points-layer', filters);
            step = (step + 1) % lastStep;
            console.log('step :>> ', step);
          }, 1000 / 5);

          // const filters = ['==', 'stepFlag', 0];
          // const reFlash = () => {
          //   filters[2] = step;
          //   map.setFilter('points-layer', filters);
          //   step = (step + 1) % lastStep;
          //   requestAnimationFrame(reFlash);
          // };
          // reFlash();
        });
      });

      // let dataCount = 0;
      // console.log('d[dataCount] :>> ', d[dataCount]);
      // map.getSource('point').setData(d[dataCount]);
      // setInterval(function () {
      //   this.map.getSource('point').setData(d[dataCount]);
      //   dataCount = (dataCount + 1) % sectionRange[1];
      // }, 200);

      // zoom变化时打印zoom值
      map.on('zoom', function (e) {
        console.log('zoom :>> ', e.target.getZoom());
      });
    },
    getUnixMinutes(UnixMillisecond) {
      return Math.floor(UnixMillisecond / 1000 / 60);
    },
  },
  beforeDestroy() {
    // this.map.removeLayer('custom-vector-tile-layer');
    this.map.remove();
    this.map = null;
  },
};
</script>

<style>
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}
#app {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
}
</style>
